﻿// 对Date的扩展，将 Date 转化为指定格式的String   
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，   
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)   
// 例子：   
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423   
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18   
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
Date.prototype.add = function(dateLimit) {
    if ('days' in dateLimit) {
        return new Date(this.setDate(this.getDate() + dateLimit['days']));
    } else if ('month' in dateLimit) {
        return new Date(this.setMonth(this.getMonth() + dateLimit['month']));
    } else {
        console.error('Date add/subtract support days|month ONLY.');
        return null;
    }
};
String.prototype.trim = function() { return this.replace(/(^\s*)|(\s*$)/g,""); };
String.prototype.replaceAll = function(string, replaceWith, ignoreCase) {
    if (!RegExp.prototype.isPrototypeOf(string)) {
        return this.replace(new RegExp(string, (ignoreCase ? "gi": "g")), replaceWith);
    } else {
        return this.replace(string, replaceWith);
    }
};

window.XS = {
    ajax: {
        /**
         * 公用 Ajax 方法，默认以 POST 方式提交 XS.ajax.doRequest(opts)
         * 函数 opts.success(result) 在返回参数 result == 0 时才会回调
         * 如果错误需要处理，在回调函数 opts.fail(result) 中处理
         */
        doRequest: function (opts) {
            var options = $.extend({}, XS.ajax.defaults, opts || {});
            options.success = function (result) {
                if (typeof result == 'object' && 'result' in result) {
                    if (result.result == 0) { // 成功
                        opts.success && opts.success(result);
                    } else {
                        XS.util.alert(result.message);
                        opts.fail && opts.fail(result);
                    }
                } else {
                    XS.util.alert('<p class="text-danger">请求 ' + opts.url + ' 时出现错误：</p>' + result);
                }
            };
            $.ajax(options);
        },
        defaults: {
            type: 'POST',
            url: '',
            data: {},
            success: function (result) {},
            fail: function (result) {},
            error: function (x, s, e) {
                var errorMsg = null;
                if (s == 'timeout') {
                    errorMsg = '连接超时';
                } else {
                    var errorCode = x.status;
                    if (errorCode == '401') {
                        errorMsg = '401 - 访问被拒绝';
                    } else if (errorCode == '403') {
                        errorMsg = '403 - 禁止访问';
                    } else if (errorCode == '404') {
                        errorMsg = '404 - 未找到';
                    } else if (errorCode == '500') {
                        errorMsg = '500 - 内部服务器错误';
                    } else if (errorCode == '12029') {
                        errorMsg = '无法建立HTTP连接';
                    } else {
                        errorMsg = e;
                    }
                }
                errorMsg && XS.util.alert(errorMsg);
            }
        }
    },
    validation: {
        isTelephone: function (text) {
            return /^0?1\d{10}$/.test(text);
        },
        isEmpty: function (text) {
            return !text || null == text || "" == text || "null" == text || "undefined" == text;
        }
    },
    util: {
        /**
         * 弹出窗口
         * @param title 标题
         * @param content 内容，可以是 html
         * @param modal 是否为模态窗口
         */
        dialog: function (title, content, modal) {
            XS.dialog.open('xs-dialog', {title: title, content: content, modal: modal});
        },
        /**
         * 重写的 alert 对话框
         * 使用回调方式： XS.util.alert('这是提示信息', {ok: function(){alert('你确定了')}, cancel: function(){alert('你取消了')}});
         * 可自定义title在options中： XS.util.alert('详细提示内容', {title: '提示'}});
         * @param message
         * @param opts
         */
        alert: function (message, opts) {
            var _opts = $.extend({}, {title: '提示', content: message, okBtn: true}, opts || {});
            XS.dialog.open('xs-alert', _opts);
        },
        /**
         * 确认对话框
         * 使用回调方式： XS.util.confirm('你确定？', {ok: function(){alert('你确定了')}, cancel: function(){alert('你取消了')}});
         * 可自定义title在options中： XS.util.confirm('详细提示内容', {title: '提示'}});
         * @param message
         * @param opts
         */
        confirm: function (message, opts) {
            var _opts = $.extend({}, {title: '提示', content: message, okBtn: true, cancelBtn: true}, opts || {});
            XS.dialog.open('xs-confirm', _opts);
        },
        /**
         * 解析当前 url 中的参数
         * 如： http://www.baidu.com/a.html?a=1&b=true 将返回 {a: '1', b: 'true'}
         */
        getUrlParams: function () {
            var params = {};
            var search = location.search;
            if (!XS.validation.isEmpty(search)) {
                search = search.substring(1);
                var p = [];
                if (search.indexOf('&') > -1) {
                    p = search.split('&');
                } else {
                    p = [search];
                }
                if (p.length) {
                    for (var i in p) {
                        var b = p[i];
                        if (b.indexOf('=') > -1) {
                            var map = b.split('=');
                            if (map.length == 2) {
                                params[map[0]] = map[1];
                            }
                        }
                    }
                }
            }
            return params;
        },
        countTimer: function (target, interval, callback) {
            var $target = $(target);
            window.countTimer = {time: interval, oldText: XS.util.text($target), timer: 0};
            $target.attr({disabled: 'disabled'});
            if (!window.countTimer.timer) {
                callback && callback();
                window.countTimer.timer = setInterval(function () {
                    window.countTimer.time--;
                    if (window.countTimer.time <= 0) {
                        XS.util.text($target, window.countTimer.oldText);
                        window.countTimer.timer = 0;
                        clearInterval(window.countTimer.timer);
                        $target.removeAttr('disabled');
                        return;
                    }
                    var text = window.countTimer.time + '秒重新获取';
                    XS.util.text($target, text);
                }, 1000);
            }
        },
        text: function (elem, text) {
            var $target = $(elem);
            var valSupport = $target.is(':input') && !$target.is('button');
            return text ? (valSupport ? $target.val(text) : $target.text(text)) : (valSupport ? $target.val() : $target.text());
        },
        menuActive: function($menus, opts) {
            var _opts = $.extend({}, {cookie: null, callback: function(menu){}}, opts || {});

            var active = -1, index = 0;
            if (_opts.cookie) {
                var activeValue = $.cookie(_opts.cookie);
                index = 0;
                $menus.each(function(){
                    var value = $(this).attr('data-value');
                    if (value == activeValue) {
                        active = index;
                        return false;
                    }
                    index ++;
                });
            }
            if (active == -1) {
                active = 0;
            }

            index = 0;
            $menus.each(function(){
                if (index == active) {
                    activeMenu(this);
                }
                $(this).bind('click', function(){
                    if ($(this).hasClass('active')) return;
                    activeMenu(this);
                });
                index ++;
            });

            function activeMenu(elem) {
                $menus.removeClass('active');
                var $menu = $(elem);
                $menu.addClass('active');
                if (_opts.cookie) {
                    $.cookie(_opts.cookie, $menu.attr('data-value'), 365);
                }
                _opts.callback && _opts.callback(elem);
            }
        },
        mainMenuToggle: function(callback) {
            var $toggles = $('.menu-toggle');
            if (!$toggles.length) return;

            $toggles.each(function(){
                var $toggle = $(this);
                $toggle.bind('click', function () {
                    toggleMenu(this, true);
                });
                var maskSelector = $toggle.attr('data-toggle-mask');
                $(maskSelector).bind('click', function(){
                    toggleMenu($toggle, true);
                });
            });

            function toggleMenu(e, inside) {
                var $this = $(e);
                var targetSelector = $this.attr('data-toggle-target');
                var toggleClass = $this.attr('data-toggle-class');
                var $target = $(targetSelector);
                var show = !$target.hasClass(toggleClass);
                if (show) {
                    inside && $target.addClass(toggleClass);
                } else {
                    $target.removeClass(toggleClass);
                }
                callback && callback($target, show);
            }
            return { toggle: function() { toggleMenu($toggles, false); }};
        },
        halfUp: function(val, scale, ignoredZero) {
            var result = (Math.round(val * Math.pow(10, 2)) / Math.pow(10, 2));
            var resultVal = null;
            if (typeof scale == 'number' && scale >= 0) {
                resultVal = result.toFixed(scale);
            }
            if (ignoredZero) {
                var i = 0, fixed, floatVal = parseFloat(resultVal);
                for (; i <= scale; i++) {
                    var temp = result.toFixed(i);
                    if (floatVal == temp) {
                        fixed = temp;
                        break;
                    }
                }
                return fixed;
            }
            return result;
        },
        /**
         * Copy from highlight charts
         * Format a number and return a string based on input settings
         * @param {Number} number The input number to format
         * @param {Number} decimals The amount of decimals
         * @param {String} decPoint The decimal point, defaults to the one given in the lang options
         * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options
         */
        numberFormat: function (number, decimals, decPoint, thousandsSep) {
            var setting = {decimalPoint: '.', thousandsSep: ','},
            // http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/
                n = +number || 0,
                c = decimals === -1 ?
                    (n.toString().split('.')[1] || '').length : // preserve decimals
                    (isNaN(decimals = Math.abs(decimals)) ? 2 : decimals),
                d = decPoint === undefined ? setting.decimalPoint : decPoint,
                t = thousandsSep === undefined ? setting.thousandsSep : thousandsSep,
                s = n < 0 ? "-" : "",
                i = String(parseInt(n = Math.abs(n).toFixed(c)), 10),
                j = i.length > 3 ? i.length % 3 : 0;

            return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) +
                (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
        },
        /**
         * 将金额（分）转换为元
         * @param val 分
         * @param prefix 前缀，如￥
         */
        toAmount: function(val, prefix){
            return (prefix ? prefix : '') + XS.util.numberFormat(val / 100, 2);
        }
    },
    dialog: {
        open: function (id, opts) {
            var _opts = $.extend({}, XS.dialog.defaults, opts || {});
            $('#' + id).remove();
            $('.modal-backdrop').remove();
            var dialog = $('<div id="' + id + '" class="modal fade">' +
            '<div class="modal-dialog"><div class="modal-content">' +
            '<div class="modal-header">' +
            '<a href="javascript:void(0)" class="close">&times;</a>' +
            '<h4 class="modal-title">' + _opts.title + '</h4></div>' +
            '<div class="modal-body"><div class="modal-body-content"></div></div>' +
            '</div></div></div>');
            dialog.find('.close').bind('click', function () {
                XS.dialog.close(id);
                _opts.cancel && _opts.cancel();
            });
            $('body').append(dialog);
            if (opts.modal) {
                dialog.addClass('modal');
            }
            var content = dialog.find('.modal-body-content');
            content.css({
                minWidth: _opts.width,
                minHeight: _opts.height
            });
            content.html(_opts.content);
            if (_opts.okBtn || _opts.cancelBtn) {
                var footer = $('<div class="modal-footer"></div>');
                if (_opts.okBtn) {
                    var ok = $('<button type="button" class="btn btn-primary">确定</button>');
                    footer.append(ok);
                    ok.bind('click', function () {
                        XS.dialog.close(id);
                        _opts.ok && _opts.ok();
                    });
                }
                if (_opts.cancelBtn) {
                    var cancel = $('<button type="button" class="btn btn-default">取消</button>');
                    footer.append(cancel);
                    cancel.bind('click', function () {
                        XS.dialog.close(id);
                        _opts.cancel && _opts.cancel();
                    });
                }
                dialog.find('.modal-content').append(footer);
            }
            dialog.modal({backdrop: 'static'});
        },
        close: function (id) {
            $("#" + id).modal("hide");
        },
        render: function (id, content) {
            $('#' + id).find('.modal-body-content').html(content);
        },
        defaults: {
            title: '',
            width: 300,
            height: 'auto',
            url: null,
            content: null,
            modal: true,
            okBtn: false,
            cancelBtn: false,
            ok: function () {},
            cancel: function () {}
        }
    }
};
